using Godot;
using System;

public partial class Player : CharacterBody2D
{
	[Export] public float Speed = 150.0f;
	[Export] public int AttackDamage = 5;
	[Export] public int MaxHealth = 100;
	private int currentHealth;
	private AnimatedSprite2D animatedSprite;
	private bool isAttacking = false;
	private Area2D attackArea;
	private CollisionShape2D attackCollision;
	private Vector2 attackAreaOffset; // 保存攻击区域的初始偏移量
	private Area2D hurtBox;
	private TextureProgressBar healthBar;
	private bool isDead = false;

	public override void _Ready()
	{
		// 获取节点
		animatedSprite = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
		attackArea = GetNode<Area2D>("AttackArea");
		attackCollision = GetNode<CollisionShape2D>("AttackArea/CollisionShape2D");
		hurtBox = GetNode<Area2D>("HurtBox");
		healthBar = GetNode<TextureProgressBar>("HealthBar");
		
		// 初始化血量
		currentHealth = MaxHealth;
		healthBar.MaxValue = MaxHealth;
		healthBar.Value = currentHealth;
		
		// 保存攻击区域的初始偏移量（相对于玩家的位置）
		attackAreaOffset = attackArea.Position;
		
		// 设置攻击区域组
		attackArea.AddToGroup("player_attack");
		
		// 将玩家添加到player组
		AddToGroup("player");
		
		// 初始时禁用攻击碰撞
		attackCollision.Disabled = true;
		
		// 连接信号
		animatedSprite.AnimationFinished += OnAnimationFinished;
		hurtBox.AreaEntered += OnHurtBoxAreaEntered;
	}

	
	public override void _PhysicsProcess(double delta)
	{
		if (!isDead)
		{
			HandleMovement();
			HandleAttack();
		}
	}
	
	private void HandleMovement()
	{
		// 获取输入方向
		Vector2 direction = Vector2.Zero;
		
		if (Input.IsActionPressed("right"))
			direction.X += 1;
		if (Input.IsActionPressed("left"))
			direction.X -= 1;
		if (Input.IsActionPressed("down"))
			direction.Y += 1;
		if (Input.IsActionPressed("up"))
			direction.Y -= 1;
		
		// 标准化方向向量，防止对角线移动过快
		if (direction != Vector2.Zero)
		{
			direction = direction.Normalized();
			Velocity = direction * Speed;
			
			// 根据移动方向翻转精灵
			if (direction.X > 0)
			{
				// 向右移动，不翻转
				animatedSprite.FlipH = false;
			}
			else if (direction.X < 0)
			{
				// 向左移动，水平翻转
				animatedSprite.FlipH = true;
			}
			// 如果只是上下移动（direction.X == 0），保持当前翻转状态
			
			// 只有在不攻击时才播放跑步动画
			if (!isAttacking && animatedSprite.Animation != "run")
			{
				animatedSprite.Play("run");
			}
		}
		else
		{
			Velocity = Vector2.Zero;
			
			// 只有在不攻击时才播放待机动画
			if (!isAttacking && animatedSprite.Animation != "idle")
			{
				animatedSprite.Play("idle");
			}
		}
		
		// 移动角色
		MoveAndSlide();
	}
	
	private void HandleAttack()
	{
		// 检测J键攻击输入
		if (Input.IsActionJustPressed("attack") && !isAttacking)
		{
			// 设置攻击状态
			isAttacking = true;
			// 播放攻击动画
			animatedSprite.Play("attack_r1");
			
			// 根据角色朝向调整攻击区域位置
			if (animatedSprite.FlipH)
			{
				// 角色向左，攻击区域镜像到左侧
				attackArea.Position = new Vector2(-attackAreaOffset.X, attackAreaOffset.Y);
			}
			else
			{
				// 角色向右，攻击区域保持原始偏移位置
				attackArea.Position = attackAreaOffset;
			}
			
			// 启用攻击碰撞
			attackCollision.Disabled = false;
			
			// 设置攻击碰撞在短时间后自动禁用
			GetTree().CreateTimer(0.3f).Timeout += () => {
				attackCollision.Disabled = true;
			};
		}
	}
	
	private void OnAnimationFinished()
	{
		// 当攻击动画播放完成时，重置攻击状态
		if (animatedSprite.Animation == "attack_r1")
		{
			isAttacking = false;
			// 确保攻击碰撞被禁用
			attackCollision.Disabled = true;
		}
	}
	
	private void OnHurtBoxAreaEntered(Area2D area)
	{
		// 检查是否被敌人攻击
		if (area.IsInGroup("enemy_attack") && !isDead)
		{
			// 获取敌人的攻击伤害
			Enemy enemy = area.GetParent<Enemy>();
			if (enemy != null)
			{
				TakeDamage(enemy.AttackDamage);
			}
		}
	}
	
	public void TakeDamage(int damage)
	{
		if (isDead) return;
		
		currentHealth -= damage;
		currentHealth = Mathf.Max(0, currentHealth);
		
		// 更新血条
		healthBar.Value = currentHealth;
		
		// 显示受伤效果
		ShowHitEffect();
		
		// 检查是否死亡
		if (currentHealth <= 0)
		{
			Die();
		}
	}
	
	private void ShowHitEffect()
	{
		// 创建受伤闪烁效果
		var tween = CreateTween();
		tween.TweenProperty(animatedSprite, "modulate", Colors.Red, 0.1f);
		tween.TweenProperty(animatedSprite, "modulate", Colors.White, 0.1f);
	}
	
	private void Die()
	{
		isDead = true;
		GD.Print("玩家死亡！");
		
		// 播放死亡动画或效果
		animatedSprite.Play("idle"); // 暂时播放idle动画
		
		// 3秒后重生
		GetTree().CreateTimer(3.0f).Timeout += Respawn;
	}
	
	private void Respawn()
	{
		isDead = false;
		currentHealth = MaxHealth;
		healthBar.Value = currentHealth;
		
		// 重置位置到初始位置
		Position = new Vector2(600, 300);
		
		GD.Print("玩家重生！");
	}
}
